package com.weayer.remote;
import com.weayer.constant.AmapConfigConstants;
import com.weayer.dto.ResponseResult;
import com.weayer.response.AddTerminalResponse;
import com.weayer.response.SearchTerminalResponse;
import com.weayer.response.TrsearchResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 调用终端管理Client
 * @author: Weayer
 **/
@Service
public class MapTerminalClient {
    @Value("${amap.key}")
    private String amapKey;
    @Value("${amap.sid}")
    private String amapSid;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * @Description: 创建终端
     * @Param: [name]
     * @return: com.weayer.dto.ResponseResult<com.weayer.response.TerminalResponse>
     **/
    public ResponseResult<AddTerminalResponse> add(String name, String desc){
        // 1. 组装url:
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstants.TERMINAL_ADD_URL_PREFIX);
        urlBuilder.append("?");
        urlBuilder.append("key=" + amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid=" + amapSid);
        urlBuilder.append("&");
        urlBuilder.append("name=" + name);
        urlBuilder.append("&");
        urlBuilder.append("desc=" + desc);
        // 2. 调用高德地图api
        ResponseEntity<String> serviceEntity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);
        // 3. 解析接口
        return parseServiceEntity(serviceEntity.getBody());
    }
    public ResponseResult<AddTerminalResponse> parseServiceEntity(String serviceString){
        /**
         * {
         *     "code": 1,
         *     "message": "success",
         *     "data": {
         *         "name": "车辆2",
         *         "tid": 858944998,
         *         "sid": 1023154
         *     }
         * }
         **/
        JSONObject result = JSONObject.fromObject(serviceString);
        JSONObject data = result.getJSONObject("data");
        AddTerminalResponse terminalResponse = new AddTerminalResponse();
        terminalResponse.setName(data.getString("name"));
        terminalResponse.setSid(data.getString("sid"));
        terminalResponse.setTid(data.getString("tid"));
        return ResponseResult.success(terminalResponse);
    }
    /**
     * @Description: 搜索周边终端
     * @Param: [center, radius]
     * @return: com.weayer.dto.ResponseResult<java.util.List<com.weayer.response.SearchTerminalResponse>>
     **/
    public ResponseResult<List<SearchTerminalResponse>> search(String center, int radius){
        // 1. 组装url:
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstants.TERMINAL_AROUND_SEARCH_URL_PREFIX);
        urlBuilder.append("?");
        urlBuilder.append("key=" + amapKey);
        urlBuilder.append("&");
        urlBuilder.append("sid=" + amapSid);
        urlBuilder.append("&");
        urlBuilder.append("center=" + center);
        urlBuilder.append("&");
        urlBuilder.append("radius=" + radius);
        // 2. 调用高德地图api
        ResponseEntity<String> serviceEntity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);
        // 3. 解析接口
        //      carId: tid - 终端设备id
        //      tid: desc - 终端描述
        JSONObject result = JSONObject.fromObject(serviceEntity.getBody());
        JSONObject data = result.getJSONObject("data");
        List<SearchTerminalResponse> terminalResponses = new ArrayList<>();
        JSONArray results = data.getJSONArray("results");
        for(int i = 0; i < results.size(); ++i){
            SearchTerminalResponse terminalResponse = new SearchTerminalResponse();
            JSONObject obj = results.getJSONObject(i);
            JSONObject locationObj = obj.getJSONObject("location");
//            response.setCarId(obj.getLong("desc"));
            terminalResponse.setCarId(Long.parseLong(obj.getString("desc")));   // 防止强制转换精度丢失
            terminalResponse.setTid(obj.getString("tid"));
            terminalResponse.setLongitude(locationObj.getString("longitude"));
            terminalResponse.setLatitude(locationObj.getString("latitude"));
            terminalResponses.add(terminalResponse);
        }
        return ResponseResult.success(terminalResponses);
    }

    /**
     * @Description: 查询轨迹
     * @Param: [tid, starttime, endtime]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult<TrsearchResponse> trsearch(String tid, Long starttime , Long endtime){
        // 拼装请求的url
        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.TERMINAL_SEARCH);
        url.append("?");
        url.append("key="+amapKey);
        url.append("&");
        url.append("sid="+amapSid);
        url.append("&");
        url.append("tid="+tid);
        url.append("&");
        url.append("starttime="+starttime);
        url.append("&");
        url.append("endtime="+endtime);

        System.out.println("高德地图查询轨迹结果请求："+url.toString());
        ResponseEntity<String> forEntity = restTemplate.getForEntity(url.toString(), String.class);
        JSONObject result = JSONObject.fromObject(forEntity.getBody());
        JSONObject data = result.getJSONObject("data");
        int counts = data.getInt("counts");
        if (counts == 0){
            return null;
        }
        JSONArray tracks = data.getJSONArray("tracks");
        long driveMile = 0L;
        long driveTime = 0L;
        for (int i=0;i<tracks.size();i++){
            JSONObject jsonObject = tracks.getJSONObject(i);

            long distance = jsonObject.getLong("distance");
            driveMile = driveMile + distance;

            long time = jsonObject.getLong("time");
            time = time / (1000 * 60);
            driveTime = driveTime + time;
        }
        TrsearchResponse trsearchResponse = new TrsearchResponse();
        trsearchResponse.setDriveMile(driveMile);
        trsearchResponse.setDriveTime(driveTime);
        return ResponseResult.success(trsearchResponse);

    }
}
